package cn.gson.CRM.controller;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.gson.CRM.model.dao.customers.CustomersDao;
import cn.gson.CRM.model.dao.fund.PayPlanDao;
import cn.gson.CRM.model.dao.fund.PayRecordDao;
import cn.gson.CRM.model.dao.fund.ReceivePlanDao;
import cn.gson.CRM.model.dao.fund.ReceiveRecordDao;
import cn.gson.CRM.model.dao.order.OrderDao;
import cn.gson.CRM.model.dao.permission.MemberDao;
import cn.gson.CRM.model.dao.product.PurchaseDao;
import cn.gson.CRM.model.dao.server.ServerDao;
import cn.gson.CRM.model.dao.stock.InOutDao;
import cn.gson.CRM.model.entity.Customer.LifeTime;
import cn.gson.CRM.model.entity.Member;
import cn.gson.CRM.model.entity.Resource;
import cn.gson.CRM.utils.Constants;
import cn.gson.CRM.utils.VerifyCodeUtils;
import cn.gson.CRM.model.entity.Purchase.State;
import cn.gson.CRM.model.entity.ReceivePlan;
/**
* @author 邓安民:
* @version 创建时间：2018年4月7日 下午5:56:50
* 登陆
*/

@Controller
public class LoginController {
	
	@Autowired
	MemberDao memberDao;
	
	@Autowired
	ServerDao serverDao;
	
	@Autowired
	PurchaseDao purDao;
	
	@Autowired
	PayPlanDao payPlanDao;
	
	@Autowired
	ReceivePlanDao receivePlanDao;
	
	@Autowired
	PayRecordDao payDao;
	
	@Autowired
	ReceiveRecordDao reDao;
	
	@Autowired
	CustomersDao ctDao;
	
	@Autowired
	OrderDao orDao;
	
	@Autowired
	InOutDao ioDao;
	
	@GetMapping("/login")
	public String toLogin(){
		return "backLogin";
		
	}
	/**
	 * 验证码
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
   @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void captcha(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		// 生成验证码的随机字符串
		String code = VerifyCodeUtils.generateVerifyCode(4);
		// 将随机字符串存入session
		request.getSession().setAttribute(Constants.CAPTCHA_CODE_SESSION_KEY, code);
		// 输出图片
		VerifyCodeUtils.outputImage(135, 44, response.getOutputStream(), code);
    }
	
	@GetMapping("/index")
	public String toIndex(HttpSession session,RedirectAttributes r,Model model){
		r.addFlashAttribute("member", session.getAttribute("member"));
		//model.addAttribute("serverCount", serverDao.countByState());
		model.addAttribute("serverCount", serverDao.countByState());
		//采购单未付款
		model.addAttribute("purNopay", purDao.findByCount(State.NOPAY));
		//采购单无产品
		model.addAttribute("purNodetail", purDao.findByCount(State.NODETAIL));
		//采购单已付款
		model.addAttribute("purPayed", purDao.findByCount(State.PAYED));
		//采购单已付款
		model.addAttribute("purCount", purDao.countByState());
		
		//订单相关信息
		//待付款
		model.addAttribute("orderXIA",orDao.findOrderByState(cn.gson.CRM.model.entity.Order.State.XIA));
		//待发货
		model.addAttribute("orderPAY",orDao.findOrderByState(cn.gson.CRM.model.entity.Order.State.PAY));
		//待确认收货
		model.addAttribute("orderSEND",orDao.findOrderByState(cn.gson.CRM.model.entity.Order.State.SEND));
		//上月完成订单数
		model.addAttribute("orderLastMonth",orDao.findOrderByLastMonth());
		//本月完成订单数
		model.addAttribute("orderMonth",orDao.findOrderByMonth());
		
		//财务相关信息
		model.addAttribute("payPlanCount", payPlanDao.countByState());
		model.addAttribute("receivePlanCount", receivePlanDao.countByState());
		model.addAttribute("paySum", payDao.countByState());
		model.addAttribute("receiveSum", reDao.countByState());
		
		//客户相关信息
		model.addAttribute("ctNO",ctDao.findCustomerNo(LifeTime.NO));
		model.addAttribute("ctLATENT",ctDao.findCustomerNo(LifeTime.LATENT));
		model.addAttribute("ctSIGN",ctDao.findCustomerNo(LifeTime.SIGN));
		model.addAttribute("ctREPEAT",ctDao.findCustomerNo(LifeTime.REPEAT));
		model.addAttribute("ctTodayCount",ctDao.findCustomerBirToday());
		model.addAttribute("ctMonCount",ctDao.findCustomerBir());
		
		//库存客户相关信息
		model.addAttribute("inNodeal",ioDao.findInNodeal());
		model.addAttribute("inCount",ioDao.findInCount());
		model.addAttribute("inReject",ioDao.findInReject());
		model.addAttribute("outNodeal",ioDao.findOutNodeal());
		model.addAttribute("outCount",ioDao.findOutCount());
		model.addAttribute("outReject",ioDao.findOutReject());
		return "index";
	}
	
	@PostMapping("login")
	public String doLogin(@RequestParam String account, @RequestParam String password,
			@RequestParam String  yanzheng,
			HttpSession session,
			RedirectAttributes r){
		
		Member m = memberDao.findOneByAccount(account);//DigestUtils.md2Hex(password)
		if (m != null && m.getEnable() && m.getPassword().equals(password)
			&&yanzheng.equalsIgnoreCase((String) session.getAttribute(Constants.CAPTCHA_CODE_SESSION_KEY))//判断验证码是否相等 
			) {
			session.setAttribute("member", m);
			r.addFlashAttribute("member", m);
			
			Set<Resource> resources = new HashSet<>();

			m.getRoles().forEach(role -> {
				resources.addAll(role.getResources());
			});

			// 取出菜单
			List<Resource> menus = new ArrayList<>();
			Set<String> urls = new HashSet<>();
			Set<String> identifys = new HashSet<>();
			resources.forEach(resource -> {
				if (resource.getType().equals(Resource.Type.MENU)) {
					menus.add(resource);
				}

				identifys.add(resource.getIdentify());
				if (!StringUtils.isEmpty(resource.getUrls())) {
					urls.addAll(Arrays.asList(resource.getUrls().split(",")));
				}
			});

			List<Resource> tree = new ArrayList<>();
			menus.forEach(rs -> {
				if (rs.getParent() == null) {
					this.recursion(menus, rs);
					tree.add(rs);
				}
			});
			// 将权限相关的所有信息存入 session
			session.setAttribute("menus", tree);
			session.setAttribute("urls", urls);
			session.setAttribute("identifys", identifys);
			
			return "redirect:/index";
		}
		// 重定向参数
		if(m==null){
			r.addFlashAttribute("err", "该账户不存在!");
		}else if(m != null && !m.getEnable()){
			r.addFlashAttribute("err", "该账户不可用!");
		}else if(yanzheng.equalsIgnoreCase(session.getAttribute(Constants.CAPTCHA_CODE_SESSION_KEY).toString())==false){
			r.addFlashAttribute("err",yanzheng==""?"验证码不能为空!": "验证码错误!");
		}else{
			r.addFlashAttribute("err", "密码错误!");
		}
		return "redirect:/login";
	}
	
	private void recursion(List<Resource> menus, Resource parent) {
		List<Resource> children = new ArrayList<>();
		menus.forEach(rs2 -> {
			if (rs2.getParent() != null && parent.getId() == rs2.getParent().getId()) {
				this.recursion(menus, rs2);
				children.add(rs2);
			}
		});
		parent.setChildren(children);
	}
	
	@RequestMapping("logout")
	public String logout(HttpSession session){
		session.invalidate();
		return "redirect:/login";
	}
}


 